from setting import ProjectSetting, ProjectLogSetting
import logging
from logging.handlers import RotatingFileHandler
import threading
import os
from utils.files import mkdir


PROJECT_LOG_PATH = os.path.join(ProjectSetting.LOG_DIR, ProjectLogSetting.LOG_NAME)


class ProjectLogger(object):
    _instance = None
    _lock = threading.Lock()

    def __new__(cls):
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = super(ProjectLogger, cls).__new__(cls)
        return cls._instance

    def __init__(self, log_path=PROJECT_LOG_PATH, max_log_size=ProjectLogSetting.MAX_SIZE):
        mkdir(ProjectSetting.LOG_DIR)
        if not os.path.exists(log_path):
            with open(log_path, "w") as f:
                f.write("Init project log ...\n")
        self.logger = logging.getLogger(log_path)
        self.logger.setLevel(logging.INFO)
        log_handler = RotatingFileHandler(log_path, maxBytes=max_log_size, backupCount=5)
        log_format = logging.Formatter('%(asctime)s [%(filename)s:%(lineno)d] [%(levelname)s] %(message)s')
        log_handler.setFormatter(log_format)
        self.logger.addHandler(log_handler)

    def get_logger(self):
        return self.logger


class SpiderLoger(object):
    def __init__(self, spider_name):
        log_path = os.path.join(ProjectSetting.LOG_DIR, "{}.log".format(spider_name))
        self.logger = logging.getLogger(log_path)
        self.logger.setLevel(logging.INFO)

    def get_logger(self):
        return self.logger

logger = ProjectLogger().get_logger()